package wfl.spec.edu;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MajorActivity extends AppCompatActivity implements MyListViewUtils.LoadListener{
    int a = 0;
    private MyListViewUtils listViewUtils;
    private List<String> list = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private static final String TAG = "MajorActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_major);
        Button button1=(Button)findViewById(R.id.button_1) ;
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MajorActivity.this,NewsActivity.class);
                startActivity(intent);
            }
        });
        Button button3=(Button)findViewById(R.id.button_3) ;
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MajorActivity.this,ZhinengActivity.class);
                startActivity(intent);
            }
        });
        Button button4=(Button)findViewById(R.id.button_4) ;
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MajorActivity.this,GuanyuActivity.class);
                startActivity(intent);
            }
        });
        sendRequestWihtOkhttp();
        // 初始化数据
        //addList();
        // 获取控件
        Init();
        // 适配器加载数据
        adapter = new ArrayAdapter<>(MajorActivity.this,android.R.layout.simple_expandable_list_item_1, list);
        listViewUtils.setAdapter(adapter);
    }
    private void sendRequestWihtOkhttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //构造客户端，相当于浏览器
                    OkHttpClient client=new OkHttpClient();
                    //构造请求，相当于在浏览器里输入地址
                    Request request=new Request.
                            Builder()
                            .url("http://www.yyjsx.xyz/api/message/find?messageCategory=MAJOR&start="+a)
                            .build();
                    //发送请求，相当于在浏览器回车
                    Response response = client.newCall(request).execute();
                    String responseData= response.body().string();
                    parseJson(responseData);
                    Log.d(TAG, responseData);
                    //logd,logt
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void parseJson(String jsonStr){
        try {
            JSONObject jobj = new JSONObject(jsonStr);
            String dataStr = jobj.getString("data");
            Gson gson = new Gson();
            final List<Message> messageList = gson.fromJson(dataStr, new TypeToken<List<Message>>(){}.getType());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //更新Listview
                    MessageAdapter fa = new MessageAdapter(MajorActivity.this, R.layout.news_item, messageList);
                    ListView lv = (ListView)findViewById(R.id.list_view);
                    lv.setAdapter(fa);
                    lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Message message=messageList.get(position);
                            Intent intent=new Intent(MajorActivity.this,ActivityFirst.class);
                            intent.putExtra("1",message.getId());
                            startActivity(intent);
                        }
                    });
                }
            });
            for (Message m : messageList){
                Log.d(TAG,m.getPreview());
                Log.d(TAG, m.getTitle());
                Log.d(TAG,m.getSummary());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //上拉下拉
    private void Init() {
        listViewUtils = (MyListViewUtils) findViewById(R.id.list_view);
        listViewUtils.setInteface(this);
    }
    //这是上拉刷新添加的数据
    @Override
    public void onLoad() {
        // 设置延时三秒获取时局，用于显示加载效果
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 这里处理请求返回的结果（这里使用模拟数据
                // 更新数据
                adapter.notifyDataSetChanged();
                // 加载完毕
                listViewUtils.loadComplete();
            }
        }, 3000);
    }
    //这是下拉刷新添加的数据
    @Override
    public void PullLoad() {
        // 设置延时三秒获取时局，用于显示加载效果
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 这里处理请求返回的结果（这里使用模拟数据）
                a +=10;
                sendRequestWihtOkhttp();
                //wechatList.add("这是上拉刷新添加的数据");
                // 更新数据
                adapter.notifyDataSetChanged();
                // 加载完毕
                listViewUtils.loadComplete();
            }

        }, 3000);
    }
}
